package com.zby.service.imp;

import com.zby.common.exception.BlogException;
import com.zby.common.utils.ResultEnum;
import com.zby.mapper.CommentMapper;
import com.zby.model.pojo.Comment;
import com.zby.model.vo.CommentVo;
import com.zby.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static net.sf.jsqlparser.parser.feature.Feature.comment;

/**
 * @author wuyanzhu
 */
@Service
public class CommentServiceImp  implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Override
    public void inertComment(Comment comment) {
        if (comment.getUserId()==null || comment.getArticleId()==null){
             throw new BlogException(ResultEnum.COMMENT_ARTICLE_ID_NOT_EXIST_OR_DELETED);
        }

        if (comment.getContent()==null || comment.getContent().isEmpty()){
            throw new BlogException(ResultEnum.COMMENT_CONTENT_NOT_NULL);
        }
//        commentMapper.insert(comment);
     int black =    commentMapper.insertData(comment);
        if (black==0){
            throw new BlogException(ResultEnum.FAIL);
        }
    }

    @Override
    public List<CommentVo> selectComment(Integer id) {
//        查询所有父类评论
        List<CommentVo> parentComments = commentMapper.selectComment(id);
        // 开始递归
        findChildren(parentComments, id);
        return parentComments;
    }
//    递归查询子类评论
private void findChildren(List<CommentVo> comments, Integer articleId) {
    for (CommentVo comment : comments) {
        // 查询当前评论的子评论（注意参数顺序：文章ID是固定值，parentId是当前评论ID）
        List<CommentVo> children = commentMapper.selectFindChildren(articleId, comment.getId());
        comment.setChildren(children);
        // 递归处理子评论的子评论
        if (!children.isEmpty()) {
            findChildren(children, articleId);
        }
    }
}

}
